//
//  DTKTool.m
//  DTBaseDemo
//
//  Created by 葛悦彣 on 2023/2/14.
//

#import "DTKTool.h"
#import "YBImageBrowser.h"
#import "YBIBVideoData.h"
#import "AppDelegate.h"
#import <CoreText/CoreText.h>
@implementation DTKTool

+ (void)RoundedCornerWith:(CGFloat)radius andView:(UIView *)view{
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
}

+(void)RoundedCornerWith:(CGFloat)radius andView:(UIView *)view andWidth:(CGFloat)width andColor:(UIColor *)color {
    view.layer.cornerRadius = radius;
    view.layer.borderWidth = width;
    view.layer.borderColor = [color CGColor];
    view.layer.masksToBounds = YES;
}

+ (void)PartialRoundedCornerWith:(CGFloat)radius andView:(UIView *)view andCorner:(UIRectCorner)corner andSize:(CGRect )rect{
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = rect;
    maskLayer.path = path.CGPath;
    view.layer.mask = maskLayer;
}

+ (UILabel *)labelWithText:(NSString *)text andTextColor:(UIColor *)color andFont:(UIFont *)font {
    UILabel * titleLab = [[UILabel alloc] init];
    titleLab.text = text;
    titleLab.font = font;
    titleLab.textColor = color;
    return titleLab;
}




+ (void)YJ:(CGFloat)radius andView:(UIView *)view{
    view.layer.cornerRadius = radius;
    view.layer.masksToBounds = YES;
}
+ (void)YJBK:(CGFloat)radius andView:(UIView *)view andWidth:(CGFloat)width andColor:(UIColor *)color {
    view.layer.cornerRadius = radius;
    view.layer.borderWidth = width;
    view.layer.borderColor = [color CGColor];
    view.layer.masksToBounds = YES;
}
+ (void)YJYY:(CGFloat)radius andView:(UIView *)view andWidth:(CGFloat)width andColor:(UIColor *)color andSize:(CGSize )size andOpacity:(CGFloat)Opacity{
    view.layer.cornerRadius = radius;
    view.layer.shadowColor = color.CGColor;
    view.layer.shadowOffset = size;
    view.layer.shadowOpacity = Opacity;
    view.layer.shadowRadius = width;
}


+ (void)BFYJ:(CGFloat)radius andView:(UIView *)view andCorner:(UIRectCorner)corner andSize:(CGRect )rect{
    UIBezierPath * path = [UIBezierPath bezierPathWithRoundedRect:rect byRoundingCorners:corner cornerRadii:CGSizeMake(radius, radius)];
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = rect;
    maskLayer.path = path.CGPath;
    view.layer.mask = maskLayer;
}



+ (UILabel *)labelWithText:(NSString *)text andFont:(UIFont *)font andTextColor:(UIColor *)color{
    UILabel * titleLab = [[UILabel alloc] init];
    titleLab.text = text;
    titleLab.font = font;
    titleLab.textColor = color;
    return titleLab;
}
+ (NSString *)sjzf:(int)d {
    NSString *ramdom;
    NSMutableArray *array = [NSMutableArray array];
    for (int i = 1; i ; i ++) {
        int a = (arc4random() % 122);
        if (a > 96) {
            char c = (char)a;
            [array addObject:[NSString stringWithFormat:@"%c",c]];
            if (array.count == d) {
                break;
            }
        } else continue;
    }
    ramdom = [array componentsJoinedByString:@""];
    return ramdom;
}
+ (BOOL)isIponeX{
    if(@available(iOS 11.0, *)){
        if([UIApplication sharedApplication].keyWindow.safeAreaInsets.bottom > 0){
            return YES;
        }
    }
    return NO;
}

/**
 *  通过 CAShapeLayer 方式绘制虚线
 *
 *  param lineView:       需要绘制成虚线的view
 *  param lineLength:     虚线的宽度
 *  param lineSpacing:    虚线的间距
 *  param lineColor:      虚线的颜色
 *  param lineDirection   虚线的方向  YES 为水平方向， NO 为垂直方向
 **/
+ (void)drawLineOfDashByCAShapeLayer:(UIView *)lineView lineLength:(int)lineLength lineSpacing:(int)lineSpacing lineColor:(UIColor *)lineColor lineDirection:(BOOL)isHorizonal {
    
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setBounds:lineView.bounds];
    
    if (isHorizonal) {
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame))];
    } else{
        [shapeLayer setPosition:CGPointMake(CGRectGetWidth(lineView.frame) / 2, CGRectGetHeight(lineView.frame)/2)];
    }
    
    [shapeLayer setFillColor:[UIColor clearColor].CGColor];
    //  设置虚线颜色为blackColor
    [shapeLayer setStrokeColor:lineColor.CGColor];
    //  设置虚线宽度
    if (isHorizonal) {
        [shapeLayer setLineWidth:CGRectGetHeight(lineView.frame)];
    } else {
        [shapeLayer setLineWidth:CGRectGetWidth(lineView.frame)];
    }
    [shapeLayer setLineJoin:kCALineJoinRound];
    //  设置线宽，线间距
    [shapeLayer setLineDashPattern:[NSArray arrayWithObjects:[NSNumber numberWithInt:lineLength], [NSNumber numberWithInt:lineSpacing], nil]];
    //  设置路径
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, 0, 0);
    
    if (isHorizonal) {
        CGPathAddLineToPoint(path, NULL,CGRectGetWidth(lineView.frame), 0);
    } else {
        CGPathAddLineToPoint(path, NULL, 0, CGRectGetHeight(lineView.frame));
    }
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    //  把绘制好的虚线添加上来
    [lineView.layer addSublayer:shapeLayer];
}
+ (CGSize )textWithtitle:(NSString *)title andSize:(CGSize)size andFout:(UIFont *)fout {
    if(title == nil){
        return CGSizeMake(0, 0);
    }
    CGSize width = [title boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin
                                    attributes:@{NSFontAttributeName : fout}
                                       context:nil].size;
    CGFloat W = ceil(width.width);
    CGFloat H = ceil(width.height);
    
    return CGSizeMake(W, H);
}
+ (CGSize )textWithAttStr:(NSAttributedString *)attStr andSize:(CGSize)size{
    if(attStr == nil){
        return CGSizeMake(0, 0);
    }
    CGSize msize = [attStr boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin context:nil].size;
    
    msize = CGSizeMake(ceil(msize.width), ceil(msize.height));
    
    return msize;
}


+ (NSMutableAttributedString *)AttributedStringWithStr:(NSString * )str andNodeColor:(UIColor * )nodeColor andSeledColor:(UIColor *)seledColor andFont:(UIFont *)font andPattenr:(NSString *)pattenr {
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattenr options:0 error:NULL];
    if(!str){
        str = @"";
    }
    NSArray<NSTextCheckingResult *> *ranges = [regular matchesInString:str options:0 range:NSMakeRange(0, [str length])];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentNatural; //设置两端对齐显示
    paragraphStyle.hyphenationFactor = 0;
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.lineSpacing = kwt(5); // 设置行间距

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSParagraphStyleAttributeName :paragraphStyle,NSForegroundColorAttributeName : nodeColor,NSFontAttributeName:font}];

    for (int i = 0; i < ranges.count; i++) {
        [attStr setAttributes:@{NSForegroundColorAttributeName : seledColor,NSParagraphStyleAttributeName :paragraphStyle,} range:ranges[i].range];
    }
    return attStr;
}
+ (NSMutableAttributedString *)AttributedStringWithStr:(NSString * )str andNodeColor:(UIColor * )nodeColor andSeledColor:(UIColor *)seledColor andNodeFont:(UIFont *)Nodefont andFont:(UIFont *)font andPattenr:(NSString *)pattenr {
    if(!str){
        str = @"";
    }
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:pattenr options:0 error:NULL];
    
    NSArray<NSTextCheckingResult *> *ranges = [regular matchesInString:str options:0 range:NSMakeRange(0, [str length])];
    NSMutableParagraphStyle *paragraphStyle = [[NSMutableParagraphStyle alloc] init];
    paragraphStyle.alignment = NSTextAlignmentNatural; //设置两端对齐显示
    paragraphStyle.hyphenationFactor = 0;
    paragraphStyle.lineBreakMode = NSLineBreakByCharWrapping;
    paragraphStyle.lineSpacing = kwt(5); // 设置行间距

    NSMutableAttributedString *attStr = [[NSMutableAttributedString alloc] initWithString:str attributes:@{NSParagraphStyleAttributeName :paragraphStyle,NSForegroundColorAttributeName : nodeColor,NSFontAttributeName:font}];

    for (int i = 0; i < ranges.count; i++) {
        [attStr setAttributes:@{NSForegroundColorAttributeName : seledColor,NSFontAttributeName:Nodefont,NSParagraphStyleAttributeName :paragraphStyle,} range:ranges[i].range];
    }
    return attStr;
}
+ (IQTextView * )NewTextView {
    IQTextView * view = [IQTextView new];
    view.textContainer.lineFragmentPadding = 0;
    view.placeholderTextColor = KcolorHex(@"#9FA5AE");
    return view;
}
///判断版本
+ (BOOL)VersionJudgment:(NSString *)str{
    NSString * currentVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if([currentVersion isEqualToString:str]){
        return YES;
    }
    NSArray<NSString *> * cvArray = [currentVersion componentsSeparatedByString:@"."];
    NSArray<NSString *> * newArray = [str componentsSeparatedByString:@"."];
    
    for (int i = 0; i < cvArray.count ; i++) {
        if(cvArray.count > i && newArray.count > i){
            NSLog(@"%d---%d",[cvArray[i] intValue],[newArray[i] intValue]);
            if([cvArray[i] intValue] > [newArray[i] intValue]){///如果现在版本大就是最新
                return YES;
            } else if ([cvArray[i] intValue] < [newArray[i] intValue]){
                return NO;
            }
        }
    }
    
    return NO;
}

//获取当前VC
+ (UIViewController *)getCurrentVC
{
    UIViewController *rootViewController;
    if([UIApplication sharedApplication].windows.firstObject.keyWindow){
        rootViewController = [UIApplication sharedApplication].windows.firstObject.rootViewController;
    } else {
        rootViewController = [UIApplication sharedApplication].delegate.window.rootViewController;
    }

    UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
    if([rootViewController isKindOfClass:UITabBarController.class]){
        UITabBarController * vc = (UITabBarController *)rootViewController;
        UINavigationController * nac = vc.selectedViewController;
        NSArray * array = nac.viewControllers;
        if(currentVC == array.firstObject){
            return currentVC.tabBarController;
        }
    }
   
    return currentVC;
}

+ (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
    UIViewController *currentVC;
    
    if ([rootVC presentedViewController]) {
        // 视图是被presented出来的
        
        rootVC = [rootVC presentedViewController];
    }
    
    if ([rootVC isKindOfClass:[UITabBarController class]]) {
        // 根视图为UITabBarController
        
        currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
        
    } else if ([rootVC isKindOfClass:[UINavigationController class]]){
        // 根视图为UINavigationController
        
        currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
        
    } else {
        // 根视图为非导航类
        
        currentVC = rootVC;
    }
    
    return currentVC;
}
+ (NSString *)token {
//    return @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDQ5NzY1MDQsInVzZXJuYW1lIjoiZmVpZ24ifQ.Elu6epWvBISnduf-pcnYwUzPGCHO_FJAmKfqnHuvXn0";
    return [UserInfoModel shared].token;
//    return @"eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE3MDQ5NzkyODksInVzZXJuYW1lIjoiam91dGFvIn0.J5nn3aDDchGXVFFzMGSQHj7OdeS4gqDfZ5ndemiPD-s";//检验
}
+ (ACMediaPickerManager *)openXJWithType:(ACMediaPickerSource)type andLX:(BOOL)lx andBlock:(void(^)(NSArray<ACMediaModel *> * list))block{
    ACMediaPickerManager * mgr = [[ACMediaPickerManager alloc] init];
    // 定制外观
    mgr.naviBgColor = [UIColor whiteColor];
    mgr.naviTitleColor = [UIColor blackColor];
    mgr.naviTitleFont = [UIFont boldSystemFontOfSize:18.0f];
    mgr.barItemTextColor = [UIColor blackColor];
    mgr.barItemTextFont = [UIFont systemFontOfSize:15.0f];
    mgr.statusBarStyle = UIStatusBarStyleDefault;
    ///是否需要录像
    mgr.allowTakeVideo = lx;
    ///选择图片
    mgr.allowPickingImage = YES;
    //  _mgr.allowPickingGif = YES;
    mgr.maxImageSelected = 1;
    mgr.videoMaximumDuration = 15;
    mgr.pickerSource = type;
    mgr.didFinishPickingBlock = ^(NSArray<ACMediaModel *> * _Nonnull list) {
        dispatch_async(dispatch_get_main_queue(), ^{
            block(list);
        });
    };
    [mgr picker];
    return mgr;
}

+ (UIImage *)watermarkImage:(UIImage *)img withName:(NSString *)name

{
    
    NSString* mark = name;
    
    int w = img.size.width;
    
    int h = img.size.height;
    
    UIGraphicsBeginImageContext(img.size);
    
    [img drawInRect:CGRectMake(0,0 , w, h)];
    
    NSDictionary *attr = @{
        NSFontAttributeName: [UIFont boldSystemFontOfSize:20],  //设置字体
        NSForegroundColorAttributeName : [UIColor redColor]   //设置字体颜色
    };
    
    [mark drawInRect:CGRectMake(0, 0, 200,20) withAttributes:attr];         //左上角
    
    [mark drawInRect:CGRectMake(w -30,0 ,200,20) withAttributes:attr];      //右上角
    
    [mark drawInRect:CGRectMake(w - 200, h -20 ,200,20) withAttributes:attr];  //右下角
    
    //  [mark drawInRect:CGRectMake(0, h -0 , 0, 0) withAttributes:attr];    //左下角
    
    UIImage *aimg = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    return aimg;
    
}


+ (BOOL)ZZWithStr:(NSString *)Str andZZ:(NSString *)zzStr{
    NSString *regexStr = zzStr;
    NSError *error;
    NSRegularExpression *regular = [NSRegularExpression regularExpressionWithPattern:regexStr options:NSRegularExpressionCaseInsensitive error:&error];
    if (error) return NO;
    NSInteger count = [regular numberOfMatchesInString:Str options:NSMatchingReportCompletion range:NSMakeRange(0, Str.length)];
    if (count > 0) {
        return YES;
    } else {
        return NO;
    }
}
+ (BOOL)SJHPDWithStr:(NSString *)Str {
    return [DTKTool ZZWithStr:Str andZZ:@"^(13[0-9]|14[5-9]|15[0-3,5-9]|16[2,5,6,7]|17[0-8]|18[0-9]|19[1,3,5,8,9])\\d{8}$"];
}
///拨打电话
+ (void)makePhoneCalls:(NSString *)phone{
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@",phone]] options:nil completionHandler:nil];
    
}
+ (UIImage *)getVideoFirstViewImage:(NSURL *)path
{
    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:path options:nil];
    AVAssetImageGenerator *assetGen = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetGen.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.0, 1);
    NSError *error = nil;
    CMTime actualTime;
    CGImageRef image = [assetGen copyCGImageAtTime:time actualTime:&actualTime error:&error];
    UIImage *videoImage = [[UIImage alloc] initWithCGImage:image];
//    CGImageRelease(image);
    
    UIImage * bfimg = [UIImage imageNamed:@"maintenance_content_video"];
    CGFloat minW =0;
    if(videoImage.size.width > videoImage.size.height){
        minW = videoImage.size.height;
    } else {
        minW = videoImage.size.width;
    }
    UIGraphicsBeginImageContext(CGSizeMake(minW, minW));
    [videoImage drawInRect:CGRectMake(0,0,minW,minW)];
    [bfimg drawInRect:CGRectMake(minW/3,minW/3,minW/3,minW/3)];
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    
    return resultingImage;
}
///展示视频和图片
+ (void)openImagAndVideo:(NSArray <NSString *>*)urlArray andopenview:(UIView * _Nullable )view andIndex:(int)index{
    if(!view){
        view = [DTKTool getCurrentVC].view;
    }
    NSMutableArray *datas = [NSMutableArray array];
    for (NSString * url in urlArray) {
        if ([url containsString:@".mp4"] || [url containsString:@".video"] ) {
            // 网络视频
            YBIBVideoData *data = [YBIBVideoData new];
            data.videoURL = [NSURL URLWithString:url];
            data.projectiveView = view;
            [datas addObject:data];
        }  else {
            // 网络图片
            YBIBImageData *data = [YBIBImageData new];
            data.imageURL = [NSURL URLWithString:url];
            data.projectiveView = view;
            [datas addObject:data];
        }
    }
    YBImageBrowser *browser = [YBImageBrowser new];
    browser.dataSourceArray = datas;
    //这里需要加
    browser.currentPage = index;
    // 只有一个保存操作的时候，可以直接右上角显示保存按钮
    //      browser.defaultToolViewHandler.topView.operationType = YBIBTopViewOperationTypeMore;
    [browser show];
    
}
+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString
{
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return [NSDictionary dictionary];
    }
    return dic;
}
+ (NSString *)convertToJsonData:(NSDictionary *)dict {
    NSError*error;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
    NSString*jsonString;
    if(!jsonData) {
        NSLog(@"%@",error);
    }else{
        jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
    }
    NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
    //  NSRange range = {0,jsonString.length};
    //  //去掉字符串中的空格
    //  [mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
    NSRange range2 = {0,mutStr.length};
    //去掉字符串中的换行符
    [mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
    return mutStr;
}
+ (void)OpenLogin{
    AppDelegate *delegate =  (AppDelegate*)[UIApplication sharedApplication].delegate;
//    ZSLoginNewViewController *page = [ZSLoginNewViewController new];
//    delegate.window.rootViewController = page;
//    [DTNewUserInfo deleteAccount];
//    [[self getCurrentVC].view showWarning:@"请重新登陆"];
}


+(NSString *)filterHTML:(NSString *)html{
    if(html.length < 1){
        html = @"";
    }
    NSScanner * scanner = [NSScanner scannerWithString:html];
    NSString * text = @"";
    while([scanner isAtEnd]==NO)
    {
        [scanner scanUpToString:@"<" intoString:nil];
        [scanner scanUpToString:@">" intoString:&text];
        html = [html stringByReplacingOccurrencesOfString:[NSString stringWithFormat:@"%@>",text] withString:@""];
    }
    return html;
}
@end
@implementation gywbtn
@end

@implementation DTKNoClickView
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch {
    return NO;
}
@end

@implementation DTKNoClickTableView

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    NSLog(@"当前点击的 %@",NSStringFromClass([touch.view class]));
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }

    return  YES;
}
@end
